package com.oswift.gpm.web.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.gpm.entity.ErrorBean;
import com.oswift.gpm.entity.LoginBean;
import com.oswift.gpm.entity.MenuBean;
import com.oswift.gpm.entity.MessageBean;
import com.oswift.gpm.entity.SystemModuleBean;
import com.oswift.gpm.entity.UserBean;
import com.oswift.gpm.service.ILoginService;
import com.oswift.gpm.service.ISystemModuleService;
import com.oswift.gpm.service.IUserService;
import com.oswift.gpm.system.cache.LoginManager;
import com.oswift.gpm.utils.Constant;
import com.oswift.gpm.utils.PageCode;
import com.oswift.gpm.utils.Constant.OpsType;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;

@Controller
public class LoginAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(LoginAction.class);

    /**
     * spring 注入
     */
    @Resource
    private ILoginService loginService;

    /**
     * spring 注入
     */
    @Resource
    private IUserService userService;

    /**
     * spring 注入
     */
    @Resource
    private ISystemModuleService systemService;

    /**
     *
     * 加载登录页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView loadLogin(HttpServletResponse response)
    {
        ModelAndView mv = new ModelAndView(Constant.PageName.LOGIN);
        //response.setHeader("Cache-Control", "max-age=315360000");
        return mv;
    }

    /**
     *
     * 跳转到首页
     *
     * @author zhuou
     */
    @RequestMapping(value = "/goIndex", method = RequestMethod.GET)
    public String goIndex(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        HttpSession session = request.getSession();
        try
        {
            if (!StringUtil.isEmpty(id))
            {
                Object obj = session.getAttribute(Constant.SESSION_KEY);
                if (null == obj)
                {
                    return "redirect:/login.html";
                }
                UserBean userBean = (UserBean) obj;
                SystemModuleBean sysBean = systemService.getSysDetail(Integer
                        .valueOf(id));

                // 将systemId+userId的hash值放入session中
                StringBuilder sb = new StringBuilder();
                sb.append(sysBean.getSystemId());
                sb.append(userBean.getUserId());
                session.setAttribute(Constant.SESSION_KEY, sb.toString()
                        .hashCode());

                // 将登录信息写入缓存
                loginService.setCacheLoginBean(userBean, sysBean);
            }
        }
        catch (Exception e)
        {
            log.error("goIndex info is error.", e);
        }
        return "redirect:/security/index.html";
    }

    /**
     *
     * 登录后台首页
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/index", method = RequestMethod.GET)
    public ModelAndView loadIndex(HttpServletRequest request)
    {
        ModelAndView mv = null;

        try
        {
            mv = new ModelAndView(Constant.PageName.INDEX);

            LoginBean loginBean = this.getLoginBean(request);

            // 获取节点深度为0的菜单
            List<MenuBean> menuBean = loginService.getMenu(loginBean
                    .getUserId(), loginBean.getSystemId(), 0, "1");
            mv.addObject("bean", menuBean);
            mv.addObject("adminName", loginBean.getUserName());

            // 获取网站名称
            String webSitUrl = request.getServerName();
//            WebConfig webConfigBean = WebConfigManager.getValue(webSitUrl);
//            if (null != webConfigBean)
//            {
//                mv.addObject("webSiteName", webConfigBean.getSiteName());
//            }
//            else
//            {
//                mv.addObject("webSiteName", loginBean.getSystemName());
//            }
            mv.addObject("nowDate", TimeUtil
                    .getCurTimeByFormat(TimeUtil.ISO_DATE_FORMAT));
        }
        catch (Exception e)
        {
            log.error("loadIndex info is error.", e);
            mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.COMMON_ERROR);
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 登录验证
     *
     * @author zhuou
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request)
    {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String code = request.getParameter("code");

        MessageBean messBean = new MessageBean();

        try
        {
            if (StringUtil.isEmpty(userName))
            {
                messBean.setCode(PageCode.USERNAME_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.USERNAME_EMPTY));
                return messBean;
            }
            if (StringUtil.isEmpty(password))
            {
                messBean.setCode(PageCode.PASSWORD_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PASSWORD_EMPTY));
                return messBean;
            }
            if (StringUtil.isEmpty(code))
            {
                messBean.setCode(PageCode.VALIDATECODE_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_EMPTY));
                return messBean;
            }

            Object oValidataCode = request.getSession().getAttribute(
                    "validataCode");
            if (null == oValidataCode)
            {
                messBean.setCode(PageCode.VALIDATECODE_OVERTIME);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_OVERTIME));
                return messBean;
            }

            if (!code.equalsIgnoreCase(String.valueOf(oValidataCode)))
            {
                messBean.setCode(PageCode.VALIDATECODE_ERROR);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_ERROR));
                return messBean;
            }
            String lastLoginIP = request.getRemoteAddr();

            messBean = loginService.login(userName, password, lastLoginIP,
                    request.getSession());
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 登出
     *
     * @author zhuou
     */
    @RequestMapping(value = "/hLogout", method = RequestMethod.GET)
    @ResponseBody
    public Object hLogout(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            HttpSession session = request.getSession();
            if (null != session)
            {
                String hashId = String.valueOf(session
                        .getAttribute(Constant.SESSION_KEY));
                if (null != hashId && !"".equals(hashId))
                {
                    LoginManager.remove(hashId);
                    log.info("Logout Success.hashId=" + hashId);
                }

                // 删除session
                session.removeAttribute(Constant.SESSION_KEY);
            }
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.LOGOUT_SUCCESS));
        }
        catch (Exception e)
        {
            log.error("Fail to Logout. Message=" + e.getMessage());
            messBean.setCode(PageCode.LOGOUT_FAIL);
            messBean.setContent(ResourceManager.getValue(PageCode.LOGOUT_FAIL)
                    + "，Message=" + e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 获取用户下的所有系统
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getUserSys", method = RequestMethod.GET)
    @ResponseBody
    public Object getUserSystem(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            Object obj = request.getSession()
                    .getAttribute(Constant.SESSION_KEY);
            if (null == obj)
            {
                messBean.setCode(PageCode.SESSION_OVERTIME);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.SESSION_OVERTIME));
                return messBean;
            }
            UserBean userBean = (UserBean) obj;
            List<SystemModuleBean> sysList = userService.getSysByUserId(String
                    .valueOf(userBean.getUserId()));

            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setObjContent(sysList);
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 跳转到错误页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public ModelAndView errorPage(HttpServletRequest request)
    {
        ErrorBean bean = null;

        ModelAndView mv = new ModelAndView(Constant.PageName.ERROR_PAGE);
        Object obj = request.getAttribute("bean");
        if (null != obj)
        {
            bean = (ErrorBean) obj;
        }
        mv.addObject("bean", bean);

        return mv;
    }

    /**
     *
     * 获取一级下的子菜单
     *
     * @author zhuou
     */
    @RequestMapping(value = "/security/menu", method = RequestMethod.GET)
    @ResponseBody
    public Object getMenu(HttpServletRequest request)
    {
        String sOpsId = request.getParameter("id");
        MessageBean messBean = new MessageBean();

        if (StringUtil.isEmpty(sOpsId))
        {
            messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.GET_WEBPARAM_FAIL));
            return messBean;
        }

        try
        {
            int iOpsId = Integer.valueOf(sOpsId);
            LoginBean loginBean = this.getLoginBean(request);
            List<MenuBean> list = loginService.getMenu(loginBean.getUserId(),
                    loginBean.getSystemId(), 0, "1,2,3");

            StringBuilder html = new StringBuilder();
            for (MenuBean bean1 : list)
            {
                if (iOpsId == bean1.getParentId())
                {
                    html
                            .append("<div id=\"menuDiv_"
                                    + bean1.getOpsId()
                                    + "\" class=\"leftHeadOpen\" onclick=\"changeLeftMenu('menuDiv_"
                                    + bean1.getOpsId() + "','menuUl_"
                                    + bean1.getOpsId() + "')\">"
                                    + bean1.getOpsName() + "</div>");
                    html.append("<ul id= menuUl_" + bean1.getOpsId() + ">");

                    for (MenuBean bean2 : list)
                    {
                        if (bean1.getOpsId() == bean2.getParentId()
                                && OpsType.OPERATION != bean2.getOpsType())
                        {
                            html.append("<li><a id=\"menuLi_");
                            html.append(bean2.getOpsId());
                            html.append("\" onclick=\"openMenu('menuLi_");
                            html.append(bean2.getOpsId());
                            html.append("','");
                            html.append(bean2.getOpsId());
                            html.append("','");
                            html.append(request.getContextPath());
                            html.append(bean2.getOpsUrl());
                            html.append("');\">");
                            html.append(bean2.getOpsName());
                            html.append("</a></li>");
                        }
                    }

                    html.append("</ul>");
                }
            }
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setContent(html.toString());
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 加载修改密码页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdatePwd", method = RequestMethod.GET)
    public ModelAndView loadUpdatePwd(HttpServletRequest request)
    {
        ModelAndView mv = new ModelAndView(Constant.PageName.UPDATEPWD);

        return mv;
    }

    /**
     *
     * 修改密码方法
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    public Object updatePwd(HttpServletRequest request)
    {
        MessageBean messBean = null;
        String oldPwd = request.getParameter("oldPwd");
        String newPwd1 = request.getParameter("newPwd1");
        String newPwd2 = request.getParameter("newPwd2");

        try
        {
            if (StringUtil.isEmpty(oldPwd) || StringUtil.isEmpty(newPwd1)
                    || StringUtil.isEmpty(newPwd2))
            {
                messBean = new MessageBean();
                messBean.setCode(PageCode.PASSWORD_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PASSWORD_EMPTY));
                return messBean;
            }

            // 密码是否一致
            if (!newPwd1.equals(newPwd2))
            {
                messBean = new MessageBean();
                messBean.setCode(PageCode.LOGIN_PASSWORD_ERROR);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.LOGIN_PASSWORD_ERROR));
                return messBean;
            }

            LoginBean bean = this.getLoginBean(request);
            if (null == bean)
            {
                messBean = new MessageBean();
                messBean.setCode(PageCode.SESSION_OVERTIME);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.SESSION_OVERTIME));
                return messBean;
            }
            messBean = loginService
                    .updatePWD(bean.getUserId(), oldPwd, newPwd1);
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
    *
    * 加载后台欢迎页面
    *
    * @author zhuou
    */
   @RequestMapping(value = "/workSpace", method = RequestMethod.GET)
   public ModelAndView workSpace()
   {
       ModelAndView mv = new ModelAndView(Constant.PageName.WORKSPACE);
       return mv;
   }

    public Object quit()
    {
        return null;
    }

    public ILoginService getLoginService()
    {
        return loginService;
    }

    public void setLoginService(ILoginService loginService)
    {
        this.loginService = loginService;
    }

    public IUserService getUserService()
    {
        return userService;
    }

    public void setUserService(IUserService userService)
    {
        this.userService = userService;
    }

    public ISystemModuleService getSystemService()
    {
        return systemService;
    }

    public void setSystemService(ISystemModuleService systemService)
    {
        this.systemService = systemService;
    }
}
